#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <cstring>
#include <cerrno>
using namespace std;

#define PATH "./fifo"

class Fifo
{
public:
    Fifo(const string &s = PATH)
        : _pathName(PATH)
    {
        int n = mkfifo(_pathName.c_str(), 0666);
        if (n == 0)
        {
            cout << "mkfifo success" << endl;
        }
        else if (n < 0)
        {
            cout << "mkfifo filed, errno: " << errno << ", error_string: " << strerror(errno) << endl;
        }
    }

    ~Fifo()
    {
        int n = unlink(_pathName.c_str());
        if (n == 0)
        {
            cout << "unlink success" << endl;
        }
        else
        {
            cout << "unlinkq filed, errno: " << errno << ", error_string: " << strerror(errno) << endl;
        }
    }

private:
    string _pathName;
};

class Sync
{
public:
    Sync()
        : _wfd(-1), _rfd(-1)
    {
    }
    ~Sync()
    {
    }
    void OpenReadOrDie()
    {
        _rfd = open(PATH, O_RDONLY);
        if (_rfd < 0)
        {
            cout << "open error, errno : " << errno << ", error string : " << strerror(errno) << endl;
            exit(1);
        }
    }
    void OpenWriteOrDie()
    {
        _wfd = open(PATH, O_WRONLY);
        if (_wfd < 0)
        {
            cout << "open error, errno : " << errno << ", error string : " << strerror(errno) << endl;
            exit(1);
        }
    }
    bool Wait()
    {
        char c = 0;
        ssize_t n = read(_rfd, &c, sizeof c);
        if(n < 0)
        {
            cout << "read error" << endl;
            exit(1);
        }
        else if(n == 0)
        {
            return false;
        }
        else
        {
            return true;
        }
    }
    void WakeUp()
    {
        char c = 'a';
        ssize_t n = write(_wfd, &c, sizeof(c));
        if(n < 0)
        {
            cout << "write error" << endl;
            exit(1);
        }

    }

private:
    int _wfd;
    int _rfd;
};